package com.zg.assistant.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码工具类
 * @author zg
 */
public class QrCodeUtils {
    
    /**
     * 生成二维码
     * @param content 二维码内容
     * @param width 宽度
     * @param height 高度
     * @return 二维码图片字节数组
     */
    public static byte[] generateQrCode(String content, int width, int height) {
        try {
            Map<EncodeHintType, Object> hints = new HashMap<>();
            // 设置纠错级别
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            // 设置编码格式
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            // 设置边距
            hints.put(EncodeHintType.MARGIN, 1);
            
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
            return outputStream.toByteArray();
        } catch (WriterException | IOException e) {
            throw new RuntimeException("生成二维码失败", e);
        }
    }
    
    /**
     * 生成Base64格式的二维码
     * @param content 二维码内容
     * @param width 宽度
     * @param height 高度
     * @return Base64编码的二维码图片，格式为：
     */
    public static String generateQrCodeBase64(String content, int width, int height) {
        byte[] qrCodeBytes = generateQrCode(content, width, height);
        String base64String = Base64.getEncoder().encodeToString(qrCodeBytes);
        return "data:image/png;base64," + base64String;
    }
} 
